//
//  File.swift
//  SmartCheckIn
//
//  Created by CidyChou on 2017/8/14.
//  Copyright © 2017年 CidyChou. All rights reserved.
//

import UIKit
import CoreBluetooth

class CheckInViewController: UIViewController{
    
    let defaults = UserDefaults.standard //用户基本信息
    
    var navigationBar : UINavigationBar! //标题栏
    
    var phone :String = ""
    //是否打开蓝牙
    var bluState : Bool = false
    
    @IBOutlet weak var navigation: UINavigationBar!
    @IBOutlet weak var error: UIImageView!
    @IBOutlet weak var sCheckIn: UIImageView!
    @IBOutlet weak var btnCheckIn: UIButton!
    @IBOutlet weak var oCheckIn: UIImageView!
    @IBOutlet weak var icheckin: UIImageView!
    @IBOutlet weak var tvBlu: UITableView!
    
    var dicBluetooth = Dictionary<String, Int>()
    var bluetoothArray = [String]()
    
    //定时器
    var timer =  DispatchSource.makeTimerSource(flags: [], queue:DispatchQueue.main)
    //系统蓝牙管理对象
    var manager : CBCentralManager!
    //连接的外围
    var connectedPeripheral : CBPeripheral!
    //保存的设备特性
    var savedCharacteristic : CBCharacteristic!
    //需要连接的 CBCharacteristic 的 UUID
    var activityIndicator:UIActivityIndicatorView!
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initBlueTooth()  // 配置蓝牙
        initView()  // 配置UI
        initData()  // 配置数据
    }
    
    func initBlueTooth(){
        //配置系统蓝牙管理对象
        manager = CBCentralManager.init(delegate: self, queue: nil)
        manager.delegate = self
        
        //首次进入app 自动搜索蓝牙
        DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 0.5) {
            DispatchQueue.main.async {
                print("----------自动搜索蓝牙---------")
                self.dicBluetooth.removeAll()
                self.manager.scanForPeripherals(withServices: nil, options: nil)
            }
        }
        
        DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 4.0) {
            //操作完成，调用主线程来刷新界面
            DispatchQueue.main.async {
                print("暂停搜索")
                self.manager.stopScan()
            }
        }
        
    }
    
    func initData(){
        let userArr = defaults.array(forKey: "userInfo") ?? [Any]()  //用户基础信息
        phone = userArr[0] as! String  //用户手机
    }
    
    func initView(){
        self.error.isHidden = true
        self.sCheckIn.isHidden = true
        //btn
        btnCheckIn.backgroundColor = UIColor(red: 27/255, green: 130/255, blue: 210/255, alpha: 1)
        btnCheckIn.setTitleColor(UIColor.white, for: .normal)
        
       
    }
    
    
    @IBAction func showHistory(_ sender: Any) {
        //..  历史记录
        performSegue(withIdentifier: "history", sender: phone)
    }
    
    @IBAction func logout(_ sender: Any) {
        let array = ["","false"]
        defaults.set(array, forKey: "userInfo")
        performSegue(withIdentifier: "logout", sender: nil)
    }
    
    /// 点击 扫描蓝牙事件
    @IBAction func scanBluetooth(_ sender: Any) {
        //防止用户多次触发
        btnCheckIn.isEnabled = false
        if(bluState){
            self.btnCheckIn.setTitle("正在签到...", for: .normal)
            playAnimation()  //签到动画
            DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 0.1) {
                DispatchQueue.main.async {
                    print("延时100毫秒执行")
                    //停止扫描
                    self.manager.stopScan()
                    //清空缓存
                    self.dicBluetooth.removeAll()
                    self.manager.scanForPeripherals(withServices: nil, options: nil)
                }
            }
            
            //延时4秒执行
            DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 4.0) {
                //处理耗时操作的代码块...
                print("延时4秒执行")
                //操作完成，调用主线程来刷新界面
                DispatchQueue.main.async {
                    self.dealBluList()//处理扫描到的蓝牙
                    //停止扫描
                    self.manager.stopScan()
                }
            }
        }else{bluAlert()}
    }
    
    /// 提示用户要打开蓝牙
    func bluAlert(){
        let alertController = UIAlertController(title: "系统提示",
                                                message: "请打开蓝牙", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            print("点击了确定")
            self.btnCheckIn.isEnabled = true
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    /// 开始处理蓝牙
    func dealBluList() {
        //是否处理蓝牙为空的情况
        let jointUtils = CabineUtils(phone: phone, dicBluetooth: dicBluetooth)

        //遵守协议 展示tableiew数据
        self.tvBlu.dataSource = self
        self.tvBlu.delegate = self
        self.tvBlu.separatorStyle = UITableViewCellSeparatorStyle.none
       
        bluetoothArray = jointUtils.getBluetoothArray()
        
        //注册cell
        tvBlu.register(UITableViewCell.self, forCellReuseIdentifier: "tv_bluetooth")
        tvBlu.reloadData()
        // tableviw
        
        //server
        let serverArr = defaults.array(forKey: "serverInfo") ?? [Any]()
        
        //let ord = Int(serverArr[2])
        let array = jointUtils.getFrame(ord: serverArr[2] as! Int)//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // let array = jointUtils.getFrame(ord: serverArr[2] as! Int)
        print("拼接后的的byte数组:  -- > \(array)")
        
        // let ACKResult = SocketUtils(bytes: array).getResult()
        let ACKResult = SocketUtils(bytes: array,serverArr:serverArr)
        ACKResult.loadData {(res) -> () in
            print("服务器返回的结果:  -- > \(res)")
            if res == 1{
                self.btnCheckIn.setTitle("已签到", for: .normal)
                self.error.isHidden = true
                self.icheckin.isHidden = true
                self.sCheckIn.isHidden = false
            }else{
                self.btnCheckIn.setTitle("签到无效", for: .normal)
                
                if self.dicBluetooth.count==0 {
                    self.showElert(message: "若多次签到无效，请打开飞行模式几秒后关闭或者重启手机")
                }
                
                self.sCheckIn.isHidden = true
                self.icheckin.isHidden = false
            }
            self.oCheckIn.layer.removeAllAnimations()
            DispatchQueue.global(qos: .default).asyncAfter(deadline: DispatchTime.now() + 2.0) {
                DispatchQueue.main.async {
                    self.btnCheckIn.isEnabled = true
                }
            }
        }
    }
    
    func showElert(message msg :String){
        let alertController = UIAlertController(title: "签到无效",message: msg, preferredStyle: .alert)
        //显示提示框
        self.present(alertController, animated: true, completion: nil)
        let cancelAction = UIAlertAction(title: "好的", style: .cancel, handler: nil)
        
        alertController.addAction(cancelAction)
    }
    
    
    
    /// 设置状态栏
    func setStatusBarBackgroundColor(color : UIColor) {
        //状态栏
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        
        let statusBarWindow : UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBar : UIView = statusBarWindow.value(forKey: "statusBar") as! UIView

        if statusBar.responds(to:#selector(setter: UIView.backgroundColor)) {
            statusBar.backgroundColor = color
        }
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 20, width: self.view.bounds.size.width, height: 40))
        navigationBar.barTintColor = color
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        navigationBar.tintColor = UIColor.white
        
        let navigationItem = UINavigationItem()
        let leftItem=UIBarButtonItem(title: "签到", style: UIBarButtonItemStyle.plain, target: self, action: nil)
        navigationItem.leftBarButtonItem=leftItem
        //退出按钮
        let img=UIImage(named: "iconoff")
        let item=UIBarButtonItem(image: img, style: UIBarButtonItemStyle.plain, target: self, action: nil)
        navigationItem.rightBarButtonItem = item
        
        navigationBar.pushItem(navigationItem, animated: true)
        self.view.addSubview(navigationBar)
    }

    ///  签到动画
    func playAnimation()
    {
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 360 * 2
        anim.duration = 2
        anim.repeatCount = MAXFLOAT
        anim.isRemovedOnCompletion = true
        oCheckIn.layer.add(anim, forKey: nil)
        //oCheckIn.layer.removeAllAnimations()
        UIView.animate(withDuration: 0.2) {
            //指定旋转角度是360°
            self.oCheckIn.transform = self.oCheckIn.transform.rotated(by: CGFloat(M_PI * 2))
        }}
}

///  蓝牙
extension CheckInViewController :CBCentralManagerDelegate,CBPeripheralDelegate{
    
    func centralManagerDidUpdateState(_ central: CBCentralManager){
        
        if(central.state == .poweredOn){
            //bug
            // startScan()
            bluState = true
        }else{
            bluState = false
        }
        
        switch central.state {
        case .unknown:
            print("CBCentralManagerStateUnknown")
        case .resetting:
            print("CBCentralManagerStateResetting")
        case .unsupported:
            print("CBCentralManagerStateUnsupported")
        case .unauthorized:
            print("CBCentralManagerStateUnauthorized")
        case .poweredOff:
            print("CBCentralManagerStatePoweredOff")
        case .poweredOn:
            print("CBCentralManagerStatePoweredOn")
            //manager.scanForPeripherals(withServices: nil, options: nil) // nil 值返回所有
        }
    }
    
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
        
        if let btName = peripheral.name {
            
            if RegexUtils().doMatch(input: btName,regex: "(#)[0-9a-fA-F]{17}"){
                print("更新前 dicBluetooth\(dicBluetooth)")
                for key in dicBluetooth.keys{
                    // 前七位相同的终端为同一个终端
                    if key[0..<7] == btName[0..<7]{
                        dicBluetooth.remove(at: dicBluetooth.index(forKey: key)!) //把变化了的删掉
                    }
                }
                
                let i :Int  = Int(RSSI)
                if i < 0 {
                    dicBluetooth[btName] = RSSI as? Int
                }
                print("更新之后dicBluetooth\(dicBluetooth)")
                
            }
        }
    }
}
// tableView
extension CheckInViewController: UITableViewDataSource, UITableViewDelegate {
    
    
    //实现协议中的方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bluetoothArray.count
    }
    
    //table的cell的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: nil)
        
        let title = bluetoothArray[indexPath.row]
        let subtitle = (title as NSString).substring(with: NSMakeRange(1, 7))
        let newtitle = " 第 \(indexPath.row+1) 个 终 端 ID ：\(subtitle)"
        
        cell.textLabel?.text = newtitle
        return cell
        
    }
    
    //在这个方法中给新页面传递参数
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "history"{
            let controller = segue.destination as! WebViewController
            controller.phone = (sender as? String)!
        }
    }
}

